<?php

declare(strict_types=1);


use App\Utils\LoggerUtil;
use Hyperf\Context\ApplicationContext;
use Hyperf\Context\Context;
use function Hyperf\Translation\trans;


if (!function_exists('importLanguageBag')) {
    function importLanguageBag($fileList, $language = 'en'): array
    {
        $lang = [];
        foreach ($fileList as $file) {
            if (file_exists(BASE_PATH . '/config/language/' . strtolower($language) . '/' . $file . '.php')) {
                $lang[] = require BASE_PATH . '/config/language/' . strtolower($language) . '/' . $file . '.php';
            }
        }
        return $lang;
    }
}


if (!function_exists('formatData')) {
    /**
     * Note - 格式化返回数据
     * DateTime 2024/7/5 15:33
     * User Admin
     * @param $data
     * @param int $status
     * @param string $msg
     * @param int $code
     * @return array
     */
    function formatData($data, int $status = 200, int $code = 200, string $desc = '')
    {
        $language = Context::get('language', 'en');
        return ['data' => $data, 'status' => $status, 'code' => $code, 'desc' => trans('desc.' . $desc, [], $language)];
    }
}

if (!function_exists('logInfo')) {
    /**
     * Note - 记录日志
     * DateTime 2024/8/7 16:39
     * User Admin
     * @param $fileName - 不带后缀的文件名
     * @param $data
     */
    function logInfo($fileName, $data = [], $label = '')
    {
        LoggerUtil::write($fileName, $data, $label);
    }
}


if (!function_exists('getWealthLevel')) {
    /**
     * 获取财富值、魅力值等级
     * @param $wealth
     * @return int|mixed
     */
    function getWealthLevel($wealth)
    {
        $arr = [0, 200, 400, 800, 1600, 3200, 6400, 12800, 25600, 51200, 100000, 150000, 200000, 250000, 300000, 350000, 400000, 450000, 500000, 550000, 600000, 660000, 720000, 780000, 840000, 900000, 960000, 1020000, 1080000, 1140000, 1200000, 1260000, 1320000, 1380000, 1440000, 1500000, 1560000, 1620000, 1680000, 1740000, 1800000, 1870000, 1940000, 2010000, 2080000, 2150000, 2220000, 2290000, 2360000, 2430000, 2500000, 2570000, 2640000, 2710000, 2780000, 2850000, 2920000, 2990000, 3060000, 3130000, 3500000, 5000000, 6500000, 8000000, 9500000, 11000000, 12500000, 14000000, 15500000, 17000000, 18500000, 20000000, 21500000, 23000000, 24500000, 26000000, 27500000, 29000000, 30500000, 32000000, 35000000, 37000000, 39000000, 41000000, 43000000, 45000000, 47000000, 49000000, 51000000, 53000000, 55000000, 57000000, 59000000, 61000000, 63000000, 65000000, 67000000, 69000000, 71000000, 73000000];
        $level = 0;
        foreach ($arr as $key => $score) {
            if ($wealth >= $score) {
                $level = $key + 1;
            } else {
                break;
            }
        }
        return $level;
    }
}


if (!function_exists('getWealthLevelEx')) {
    /**
     * 当前等级，下一级，当等级值和下一级值的差，当前等级值到下一等级值完成的百分比
     * @param $wealth
     * @return int|mixed
     */
    function getWealthLevelEx($wealth)
    {
        $arr = [0, 200, 400, 800, 1600, 3200, 6400, 12800, 25600, 51200, 100000, 150000, 200000, 250000, 300000, 350000, 400000, 450000, 500000, 550000, 600000, 660000, 720000, 780000, 840000, 900000, 960000, 1020000, 1080000, 1140000, 1200000, 1260000, 1320000, 1380000, 1440000, 1500000, 1560000, 1620000, 1680000, 1740000, 1800000, 1870000, 1940000, 2010000, 2080000, 2150000, 2220000, 2290000, 2360000, 2430000, 2500000, 2570000, 2640000, 2710000, 2780000, 2850000, 2920000, 2990000, 3060000, 3130000, 3500000, 5000000, 6500000, 8000000, 9500000, 11000000, 12500000, 14000000, 15500000, 17000000, 18500000, 20000000, 21500000, 23000000, 24500000, 26000000, 27500000, 29000000, 30500000, 32000000, 35000000, 37000000, 39000000, 41000000, 43000000, 45000000, 47000000, 49000000, 51000000, 53000000, 55000000, 57000000, 59000000, 61000000, 63000000, 65000000, 67000000, 69000000, 71000000, 73000000];
        $level = 0;
        foreach ($arr as $key => $score) {
            if ($wealth >= $score) {
                $level = $key;
            } else {
                break;
            }
        }

        $maxLevel = count($arr);
        $level1 = min($level + 1, $maxLevel);
        $level2 = min($level1 + 1, $maxLevel);
        $diff = ($level1 >= $maxLevel) ? 0 : $arr[$level1] - $wealth;
        $percent = ($level1 >= $maxLevel) ? 100 : bcdiv(strval($wealth - $arr[$level]), strval($arr[$level1] - $arr[$level]), 2) * 100;

        //   当前等级，下一级，当等级值和下一级值的差，当前等级值到下一等级值完成的百分比
        return [$level1, $level2, $diff, $percent];
    }
}


if (!function_exists('removeQueryParamVar')) {
    /**
     * 移除url的某个参数
     * @param $url
     * @param $keys array|string 需要移除的一个或者多个参数
     * @return string
     * @example $url = 'https://wei1.top?a=1&b=2&user=cccc&x=ad';
     *          $newUrl = remove_query_var($url,'user');
     *          echo $newUrl;//https://wei1.top?a=1&b=2&x=ad
     */
    function removeQueryParamVar($url, array|string $keys)
    {
        $urlSchema = parse_url($url);
        if (!empty($urlSchema['query'])) {
            parse_str($urlSchema['query'], $arr);
            if (is_array($keys)) {
                foreach ($keys as $key) {
                    if (isset($arr[$key])) {
                        unset($arr[$key]);
                    }
                }
            } else {
                if (isset($arr[$keys])) {
                    unset($arr[$keys]);
                }
            }
            $url = $urlSchema['scheme'] . '://' . $urlSchema['host'] . $urlSchema['path'];
            if (!empty($arr)) {
                $url .= '?' . http_build_query($arr);
            }
        }
        return $url;
    }
}


if (!function_exists('pushQueueMessage')) {
    /**
     * 推送消息到队列.
     * @throws Throwable
     */
    function pushQueueMessage($job, array $data = []): bool
    {
        $queueService = Applicationcontext::getcontainer()->get(App\Services\Queue\QueueService::class);
        return $queueService->push(new $job(json_encode($data)));
    }
}


if (!function_exists('pushDelayJob')) {
    /**
     * 延时执行任务
     * @param string $job
     * @param array $param 参数
     * @param int $second 延时时间（秒）
     * @return bool
     * @throws Throwable
     */
    function pushDelayJob(string $job, array $param = [], int $second = 0)
    {
        $queueService = Applicationcontext::getcontainer()->get(App\Services\Queue\QueueService::class);
        return $queueService->push(new $job(json_encode($param)), $second);
    }
}


if (!function_exists('modelToArray')) {
    /**
     * Note - Hyperf模型对象转数组
     * DateTime 2024/7/17 10:44
     * User Admin
     * @param $model
     * @return array|void
     */
    function modelToArray($model)
    {
        if ($model instanceof \Hyperf\Database\Model\Model || $model instanceof \Hyperf\Database\Model\Collection) {
            return $model->toArray();
        }
        if (is_object($model)) {
            $model = (array)$model;
        }
        if (is_array($model)) {
            foreach ($model as $key => $value) {
                $model[$key] = modelToArray($value);
            }
        }
        return $model;
    }
}


if (!function_exists('getMillisecond')) {
    function getMillisecond()
    {
        $microtime = microtime(true);
        $millisecondTimestamp = round($microtime * 100);
        return intval($millisecondTimestamp);

        // list($msec, $sec) = explode(' ', microtime());
        // $msectime =  sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        // $msectimes = substr($msectime,0,13);
        // return intval($msectimes);
    }
}


if (!function_exists('checkUserGoldCount')) {
    /**
     * 计算用户扣除的金币
     * @param $user    array 用户余额信息
     * @param $cost    int|string 消耗的总金币
     * @param $type 1赠送礼物 2通话 3聊天
     * @return array|bool
     */
    function checkUserGoldCount($user, $cost, $type)
    {

        $gift_count = 0;    // 普通金币
        $chat_count = 0;    // 聊币
        $sys_send_count = 0;    // 系统赠送金币
        $recharge_send_count = 0;    // 充值赠送金币

        switch ($type) {
            case 1:
            case 2:
                if ($user['sys_send_count'] >= $cost) {
                    $sys_send_count = $cost;
                } elseif ($user['sys_send_count'] + $user['recharge_send_count'] >= $cost) {
                    $sys_send_count = $user['sys_send_count'];
                    $recharge_send_count = $cost - $sys_send_count;
                } elseif ($user['sys_send_count'] + $user['recharge_send_count'] + $user['gift_count'] >= $cost) {
                    $sys_send_count = $user['sys_send_count'];
                    $recharge_send_count = $user['recharge_send_count'];
                    $gift_count = $cost - $sys_send_count - $recharge_send_count;
                } else {
                    return false;
                }
                break;
            case 3:
                if ($user['chat_count'] >= $cost) {
                    $chat_count = $cost;
                } elseif ($user['sys_send_count'] + $user['chat_count'] >= $cost) {
                    $chat_count = $user['chat_count'];
                    $sys_send_count = $cost - $chat_count;
                } elseif ($user['chat_count'] + $user['sys_send_count'] + $user['recharge_send_count'] >= $cost) {
                    $chat_count = $user['chat_count'];
                    $sys_send_count = $user['sys_send_count'];
                    $recharge_send_count = $cost - $chat_count - $sys_send_count;
                } elseif ($user['chat_count'] + $user['sys_send_count'] + $user['recharge_send_count'] + $user['gift_count'] >= $cost) {
                    $chat_count = $user['chat_count'];
                    $sys_send_count = $user['sys_send_count'];
                    $recharge_send_count = $user['recharge_send_count'];
                    $gift_count = $cost - $sys_send_count - $recharge_send_count - $chat_count;
                } else {
                    return false;
                }
                break;
        }
        LoggerUtil::write('check_user_gold_count', compact("gift_count", 'chat_count', 'sys_send_count', 'recharge_send_count', 'cost'));


        return compact("gift_count", 'chat_count', 'sys_send_count', 'recharge_send_count');
    }

}


if (!function_exists('formatTime')) {
    /**
     * Note - 时间格式化为今天、昨天、其他
     * DateTime 2024/8/20 10:34
     * User Admin
     * @param $time
     * @param $language
     * @return array|string
     */
    function formatTime($time, $language)
    {
        $today_time = strtotime(date("Y-m-d 00:00:00"));
        $yesterday_time = strtotime(date("Y-m-d 00:00:00", strtotime("-1 days")));
        if ($time >= $today_time) {
            return trans('message.今天', ['time' => date("H:i:s", $time)]);
        } elseif ($time >= $yesterday_time) {
            return trans('message.昨天', ['time' => date("H:i:s", $time)]);
        } else {
            return date("Y-m-d H:i:s", $time);
        }
    }
}


if (!function_exists('formatSecond')) {
    /**
     * Note - 时间戳格式化为 00:00:00
     * DateTime 2024/8/20 10:40
     * User Admin
     * @param $seconds
     * @return string
     */
    function formatSecond($seconds)
    {
        if ($seconds == 0) return '0';
        if ($seconds >= 3600) {
            $time = date('H:i:s', $seconds);
        } elseif ($seconds >= 60) {
            $time = date('i:s', $seconds);
        } else {
            $time = date('00:s', $seconds);
        }
        return $time;
    }
}

